package com.neusoft.controller;

import com.neusoft.pojo.User;
import com.neusoft.service.CartService;
import com.neusoft.utils.Pages;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 
 * @author 新
 *	购物车相关的controller层
 */
@Controller
public class CartController {
	
	@Autowired
	private CartService cartService;
	
	/**
	 * 
	 * @param pid 产品ID
	 * @param pquantity 产品数量
	 * @return 返回到购物车页面
	 */
	@RequestMapping("shopping")
	public String shop(Integer pid,Integer pquantity,HttpSession session,HttpServletRequest request) {
		//获取用户信息
		User user = (User)session.getAttribute("user");
		//调用service层方法添加一条记录到购物车
		cartService.addToCart(pid, pquantity,user.getUid());
		
		//购物车列表分页的设置
		Pages pages = new Pages();
		int totalCount = cartService.countCart(user.getUid());
		pages.setTotalCount(totalCount);
		pages.setCurrenPage(1);

		request.setAttribute("cartList", cartService.getCartList(user.getUid(), pages.getCurrenPage(), pages.getPageSize()));
		request.setAttribute("totalMoney", cartService.countPrice(user.getUid()));
		request.setAttribute("pages", pages);
		return "cart";
	}
	
	/**
	 * 
	 * @param currentPage 当前页码
	 * @return 返回到购物车页面
	 */
	@RequestMapping("showCartList")
	public String showCartList(Integer currentPage,HttpSession session,HttpServletRequest request) {
		//获取用户信息
		User user = (User)session.getAttribute("user");
		
		//分页设置
		Pages pages = new Pages();
		int totalCount = cartService.countCart(user.getUid());
		pages.setTotalCount(totalCount);
		//如果为空，设置当前页为第一页
		if(currentPage == null) {
			pages.setCurrenPage(1);
		}else {
			pages.setCurrenPage(currentPage);
		}
		
		request.setAttribute("cartList", cartService.getCartList(user.getUid(), pages.getCurrenPage(), pages.getPageSize()));
		request.setAttribute("totalMoney", cartService.countPrice(user.getUid()));
		request.setAttribute("pages", pages);
		return "cart";
	}
	
	/**
	 * @param cid 购物Id
	 * @return 重定向到购物车页面
	 */
	@RequestMapping("deleteCart")
	public String deleteCart(Integer cid) {
		cartService.deleteCart(cid);
		return "redirect:showCartList";
	}
	
	
}
